<template>
  <van-nav-bar title="编辑地址" left-text="" @click-left="onClickLeft" left-arrow>
    <template #right>
      <van-icon name="location-o" size="18" v-model="flag" @click="isflag" />
    </template>
  </van-nav-bar>
  <van-address-edit :area-list="areaList" show-delete show-set-default show-search-result :search-result="searchResult"
    :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" @change-detail="onChangeDetail"
    :address-info="addressData" />
  <AMapLocation v-if="flag == true" />
</template>

<script setup>
import AMapLocation from '@/components/AMapLocation.vue'
import { ref, onMounted } from 'vue';
import { showToast } from 'vant';
import { areaList } from '@vant/area-data';
import { useRoute, useRouter } from "vue-router";
import { POST } from '../services/request';

const flag = ref(false);
const router = useRouter()
const route = useRoute();

const searchResult = ref([]);

// 获取传过来的id值
const addressId = route.query.id;
// console.log(addressId);

// 获取用户信息
const userData = JSON.parse(localStorage.getItem('LoginUser'));

const name = ref(null)
const addressData = ref({})

onMounted(async () => {
  await addressEdit();
})
// 点击定位
const isflag = async () => {
  flag.value = !flag.value

  // console.log(flag.value);
  if (flag.value == true) {
    localStorage.removeItem('addressData')
    addressData.value.areaCode = null
    setTimeout(() => {
      const locationAddress = JSON.parse(localStorage.getItem('addressData'));
      addressData.value.areaCode = locationAddress.adcode
    }, 1000)

  }
}

//获取用户已填写的值
const addressEdit = async () => {
  const editRes = await POST({
    url: '/Address/getEditAddress',
    params: {
      uid: userData.id,
      addressId: addressId
    }
  })
  if (editRes.code === 1) {
    addressData.value = editRes.data
  }
}

// 保存修改
const onSave = async (info) => {
  const saveRes = await POST({
    url: '/Address/saveEditAddress',
    params: {
      uid: userData.id,
      addressId: addressId,
      addressDetail: info.addressDetail,
      areaCode: info.areaCode,
      tel: info.tel,
      isDefault: info.isDefault,
      name: info.name,
    }
  })
  if (saveRes.code === 1) {
    // addressData.value = saveRes.data
    showToast(saveRes.msg);
    router.push('address');
  }
};
// 删除操作
const onDelete = async () => {
  const delRes = await POST({
    url: '/Address/delEditAddress',
    params: {
      uid: userData.id,
      addressId: addressId,
    }
  })
  if (delRes.code === 1) {
    showToast(delRes.msg);
    router.push('address');
  }
};


const onChangeDetail = (val) => {
  // console.log(val);

  if (val) {
    searchResult.value = [
      {
        name: `金龙华广场`,
        address: `${locationAddress.city}${locationAddress.district}`,
      },
    ];
  } else {
    searchResult.value = [];
  }
};

// 返回
const onClickLeft = () => history.back();
</script>